package com.banciyuan.bcywebview.biz.main.mineinfo.mywork;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Achievement;

/**
 * Created by squall on 2016/9/5.
 */
public class AchievementActivity extends BaseActivity implements BaseWatcher {

    private ProgressbarHelper mProgressbarHelper;
    private ListView mListView;

    private Achievement achievement;
    private LinearLayout empty;

    private RequestQueue queue;
    private View pb_share;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_achievement);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initData();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initUi() {
        mListView = (ListView) findViewById(R.id.listView);
        pb_share = findViewById(R.id.pb_share);
        empty = (LinearLayout) findViewById(R.id.empty_achievement);
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.my_achievement));
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + SpaceApi.getPostAchieve();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, AchievementActivity.this)) {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(response);
                        achievement = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), Achievement.class);
                        renderData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }


    private void renderData() {
        if (achievement.getTop_record().isEmpty()) {
            empty.setVisibility(View.VISIBLE);
            mProgressbarHelper.onSuccess();
        } else {
            empty.setVisibility(View.GONE);
            AchievementAdatper achievementAdatper = new AchievementAdatper(achievement, this);
            mListView.setAdapter(achievementAdatper);
            mProgressbarHelper.onSuccess();
        }

    }


    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.SHARE_EVENT:
                if (pb_share.getVisibility() == View.GONE) {
                    share();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(AchievementActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(AchievementActivity.class);
    }

    private void share() {
        pb_share.setVisibility(View.VISIBLE);
        String url = HttpUtils.BASE_URL + SpaceApi.getShareAchieve();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, AchievementActivity.this)) {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject img = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        goShare(img.getString("img_src"));
                    }
                } catch (Exception e) {
                    pb_share.setVisibility(View.GONE);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pb_share.setVisibility(View.GONE);
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void goShare(String path) {
        pb_share.setVisibility(View.GONE);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("content", String.format(getString(R.string.share_production), achievement.getUser().getUid()));
        map.put("title", String.format(getString(R.string.share_production_name), achievement.getUser().getUname()));
        map.put("url", "http://bcy.net/u/" + achievement.getUser().getUid());
        map.put("imagePath", path);
        Intent intent = new Intent();
        intent.setClass(this, ShareActivity.class);
        intent.putExtra("showWarnBtn", false);
        intent.putExtra("showCopyLink", false);
        intent.putExtra("map", map);
        startActivity(intent);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }
}
